package com.huatai.model.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huatai.common.api.R;
import com.huatai.model.service.BaseService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @author Lion
 * @date 2023/6/2  10:12
 */
public class BaseController<S extends BaseService,T>{

	@Autowired
	protected S service;

	@ApiOperation(value = "获取信息-单个",
		notes = "直接返回实体，未通过ResponseMessage封装",
		position = 1000)
	@ApiImplicitParam(name = "data", required = true, value = "数据主键")
	@PostMapping("/get")
	public R get(@RequestBody String data) {
		Object dbData = this.service.getById(data);
		if (dbData == null) {
			return R.fail("获取失败，数据记录[{}]不存在");
		}
		return R.data(dbData);
	}

	@ApiOperation(value = "获取数据-分页",
		notes = "采用Mybatis方式",
		position = 3000)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "data", value = "请求参数字典，具体取值如下", dataType = "Map"),
		@ApiImplicitParam(name = "data.sk_关键词[like|notlike...]_数据库字段名", value = "模糊查询关键词", dataType = "String"),
		@ApiImplicitParam(name = "data.pageIndex", value = "当前页码"),
		@ApiImplicitParam(name = "data.pageSize", value = "每页大小"),
		@ApiImplicitParam(name = "data.or_orderby", value = "排序字段，格式：排序字段(多个用逗号分隔):排序类型 asc或desc")
	})
	@PostMapping(value = "/page")
	public R page(@RequestBody JSONObject data) {
		IPage page = this.service.pageByRequestMap(data);
		this.service.buildExInfo(page.getRecords());
		return R.data(page);
	}

	@ApiOperation(value = "保存数据",
		notes = "当ID存在时，则更新，否则新增",
		position = 4000)
	@PostMapping(value = "/save")
	public R save(@ApiParam(required = true) @RequestBody T data) {
		this.service.SaveOrUpdateWithValid(data);
		return R.success("保存成功");
	}

	@ApiOperation(value = "获取数据-列表",
		notes = "采用Mybatis方式",
		position = 2000)
	@PostMapping(value = "/list")
	public R list() {
		List<Object> dbDatas = this.service.list();
		this.service.buildExInfo(dbDatas);
		return R.data(dbDatas);
	}

	@ApiOperation(value = "删除数据",
		notes = "根据主键批量删除，不验证主键是否存在",
		position = 7000)
	@ApiImplicitParam(name = "data", value = "数据主键", required = true,paramType = "list")
	@PostMapping("/delete")
	public R delete(@RequestBody List<String> data) {
		this.service.removeByIds(data);
		return R.success("success");
	}

}
